<template>
  <div class="new-contract-template">
    <div class="header">
      <a-page-header :title="title" @back="goBack" />
    </div>
    <div class="content">
      <div class="loading" v-if="pageLoading">
        <a-spin tip="数据加载中" size="large"></a-spin>
      </div>
      <a-row :gutter="[12, 12]" v-else>
        <a-col :span="16">
          <div style="height: 100%" ref="housingCard">
            <a-card size="small">
              <template #title>
                <span class="text-title">合同模板信息</span>
              </template>
              <TemplateInfo
                :validateTrigger="validateTrigger"
                @getResult="getFormResult"
              />
            </a-card>
            <!-- 合同编号 -->
            <ContractNo
              style="margin-top: 12px"
              :validateTrigger="validateTrigger"
              @getResult="getFormResult"
            />
            <a-card size="small" style="margin-top: 12px">
              <template #title>
                <span class="text-title">滞纳金条款</span>
              </template>
              <LateFee
                :validateTrigger="validateTrigger"
                @getResult="getFormResult"
              />
            </a-card>
          </div>
        </a-col>
        <a-col :span="8">
          <a-card
            v-show="housingCardHeight"
            :bodyStyle="{
              height: housingCardHeight - 60 + 'px',
              overflow: 'hidden',
            }"
            size="small"
          >
            <template #title>
              <span class="text-title">模板适用范围</span>
            </template>
            <a-alert
              v-if="disabledTree"
              show-icon
              type="warning"
              message="该审合同模板原来绑定的项目/楼宇，您未全部选中，无法修改。"
              class="mb-10"
            />
            <a-spin v-if="!showCard"  class="house-spin" tip="数据加载中"></a-spin>
            <ChooseHousingResources
              v-else
              :defaultChecked="{ roomList }"
              :areaEmptyDisabled="false"
              :showRoomArea="false"
              :allDisabled="disabledTree"
              @request="$utils.commonRequest"
              @getResult="getRoomList"
              @error="getRangeError"
              @changeTreeLoading="changeTreeLoading"
            />
          </a-card>
        </a-col>
        <a-col :span="24">
          <a-card size="small">
            <template #title>
              <span class="text-title">合同条款</span>
            </template>
            <ClauseContent
              :validateTrigger="validateTrigger"
              @getResult="getFormResult"
            />
          </a-card>
        </a-col>
      </a-row>
    </div>
    <a-row
      class="footer"
      type="flex"
      justify="end"
      align="middle"
      v-if="!pageLoading"
    >
      <a-col>
        <a-space size="large">
          <a-button @click="goBack"> 取消 </a-button>
          <a-button type="primary" :loading="submitLoading || treeLoading" @click="onSubmit">
            提交
          </a-button>
        </a-space>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { defineComponent, nextTick, reactive, toRaw, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ChooseHousingResources } from "bl-common-vue3";
import TemplateInfo from "./modules/TemplateInfo.vue";
import ContractNo from "./modules/ContractNo.vue";
import LateFee from "./modules/LateFee.vue";
import ClauseContent from "./modules/ClauseContent.vue";
import store from "../../../store/index";
import { message } from "ant-design-vue";
import request from "../../../common/utils/request";
import _ from "lodash";

export default defineComponent({
  name: "NewContractTemplate",
  components: {
    ChooseHousingResources,
    TemplateInfo,
    ContractNo,
    LateFee,
    ClauseContent,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();

    const state = reactive({
      title: "",
      id: 0,
      pageLoading: true,
      validateTrigger: 0,
      submitLoading: false,
      submitParams: {},
      roomList: [],
      housingCard: null,
      housingCardHeight: 0,
      disabledTree: false,
      treeLoading: false,
      showCard: false,
    });

    /** 获取房源 */
    const getRoomList = (detail) => {
      if (state.disabledTree) {
        return;
      }
      let roomList = _.cloneDeep(detail.roomList);
      let newArray = roomList.map((v) => {
       delete v.contract_info;
       return v;
      }); // 去除 contract_info 字段
      state.roomList = newArray;
    };
    const getRangeError = (e) => {
      if (e.type == "notFound") {
        state.disabledTree = true;
      }
    };

    const changeTreeLoading = (val) => {
      state.treeLoading = val;
    };

    /** 获取提交参数 */
    const setSubmitParams = () => {
      for (let key in formParams) {
        state.submitParams = {
          ...state.submitParams,
          ...formParams[key],
        };
      }
      console.log("------------setSubmitParams", toRaw(state.submitParams));
      submit();
    };
    const getRelationBuilds = () => {
      let relation_builds = {
        buildId: [],
        villageId: [],
        projectBuild: [],
      };
      let projectBuild = {};
      state.roomList.forEach((room) => {
        const { village_id, build_id } = room.extra;
        room.build_id = room.extra.build_id;
        room.village_id = room.extra.village_id;
        if (projectBuild[village_id]) {
          if (!projectBuild[village_id].build.includes(build_id)) {
            projectBuild[village_id].build.push(build_id);
          }
          projectBuild[village_id].room.push(room);
        } else {
          projectBuild[village_id] = {
            id: village_id,
            build: [build_id],
            room: [room],
          };
        }
      });
      for (let villageId in projectBuild) {
        relation_builds.projectBuild.push(projectBuild[villageId]);
        relation_builds.villageId.push(Number(villageId));
        relation_builds.buildId = [
          ...relation_builds.buildId,
          ...projectBuild[villageId].build,
        ];
      }
      state.submitParams.relation_builds = relation_builds;
    };

    /** 获取表单验证结果 */
    let formParams = {};
    const getFormResult = (detail) => {
      console.log("getFormResult", toRaw(detail));
      const { params, type } = detail;
      if (!params) {
        message.warning("请完善必填项！");
        resetSubmit();
        return;
      }
      // 付款时间选指定日期的特殊适配
      if (type == "ClauseContent") {
        if (params.multiple_clause && params.multiple_clause.length > 0) {
          params.multiple_clause.forEach((clause) => {
            if (
              clause.tempClauseInfo &&
              clause.tempClauseInfo.normalClause &&
              clause.tempClauseInfo.normalClause.length > 0
            ) {
              clause.tempClauseInfo.normalClause.forEach((item) => {
                if (item.payment_time_unit1 == "unit_3") {
                  delete item.payment_time_unit2;
                }
              });
            }
          });
        }
      }
      formParams[type] = params;
      if (Object.keys(formParams).length == 4) {
        setSubmitParams();
      }
    };

    /** 提交 */
    const onSubmit = () => {
      if (!state.roomList.length) {
        message.warning("请选择模板适用房源！");
        return;
      }
      resetSubmit();
      state.submitLoading = true;
      getRelationBuilds();
      state.validateTrigger++;
    };
    const resetSubmit = () => {
      formParams = {};
      state.submitParams = {};
      state.submitLoading = false;
    };

    const submit = () => {
      const params = {
        ...state.submitParams,
        needMsg: true,
      };
      let requestUrl = "/contract/clauseTemplate/add";
      let requestMethod = "post";
      if (state.id) {
        requestUrl = "/contract/clauseTemplate/edit";
        requestMethod = "put";
        params.id = state.id;
      }
      request[requestMethod]("/org", requestUrl, params)
        .then((res) => {
          message.success(res.msg || "保存成功！");
          resetSubmit();
          setTimeout(() => {
            goBack();
          }, 600);
        })
        .catch(() => {
          state.submitLoading = false;
        });
    };

    /** 返回 */
    const goBack = () => {
      if (window.history.state.back) {
        router.back();
      } else {
        router.replace({
          name: "contractTemplateList",
        });
      }
    };

    /** 获取房源列表高度 */
    let oldHeight = 0;
    const getHousingCardHeight = () => {
      state.housingCardHeight = state.housingCard.offsetHeight;
      if (!state.housingCardHeight || oldHeight != state.housingCardHeight) {
        oldHeight = state.housingCardHeight;
        setTimeout(() => {
          getHousingCardHeight();
        }, 200);
      } else {
        state.showCard = true;
      }
    };

    /** 获取详情 */
    const getDetail = () => {
      return new Promise((resolve) => {
        if (state.id) {
          request
            .get("/org", "/contract/clauseTemplate/detail", {
              id: state.id,
            })
            .then((res) => {
              store.dispatch("SetCurrentCT", res.data).then(() => {
                resolve();
              });
            });
        } else {
          store.dispatch("SetCurrentCT", {});
          resolve();
        }
      });
    };

    /** 初始化 */
    const init = () => {
      state.id = route.query.id || 0;
      state.title = state.id ? "编辑模板" : "新增模板";
      state.pageLoading = true;
      getDetail().then(() => {
        store.dispatch("GetTemplateInit").then(() => {
          state.pageLoading = false;
          // 房源回显
          if (state.id && store.getters.currentContractTpl.relation_builds) {
            const projectBuild =
              store.getters.currentContractTpl.relation_builds.projectBuild;
            let roomList = [];
            projectBuild.forEach((item) => {
              roomList = [...roomList, ...item.room];
            });
            state.roomList = roomList;
          }
          nextTick(() => {
            getHousingCardHeight();
          });
        });
      });
    };
    init();

    return {
      ...toRefs(state),
      goBack,
      onSubmit,
      getFormResult,
      getRoomList,
      getRangeError,
      changeTreeLoading,
    };
  },
});
</script>

<style lang="less" scoped>
.new-contract-template {
  height: 100%;
  padding-left: 1px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .header {
    background: #fff;
    height: 72px;
    border-bottom: 1px solid #eee;
  }
  .content {
    flex: 1;
    padding: 12px;
    overflow: hidden auto;
    .loading {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .footer {
    height: 60px;
    background: #fff;
    padding: 0 20px;
    border-top: 1px solid #eee;
  }
}
.house-spin {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>
